package other;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 法定节假日查询工具类
 *
 * @author superC
 * @version 1.0.0
 * @date 2024/4/7
 */

public class Holiday2Util {

    private static final String URL_HOLIDAY_RESULT = "https://timor.tech/api/holiday/year/";

    /**
     * 获取指定年份所有法定节假日
     *
     * @return null表示调用接口失败；
     */
    public static List<String> getHoliday2Year(String year) {
        List<String> dayList = new ArrayList<>();
        String holidayListStr = Holiday2Util.getByUrl(URL_HOLIDAY_RESULT + year);
        System.out.println(holidayListStr);
        if (StrUtil.isBlank(holidayListStr)) {
            return null;
        }
        // 解析JSON字符串为JSONObject
        JSONObject jsonObject = JSONUtil.parseObj(holidayListStr);
        // 获取holiday对象
        JSONObject holidayObj = jsonObject.getJSONObject("holiday");
        // 遍历holiday对象中的每个假期
        for (String key : holidayObj.keySet()) {
            JSONObject holidayMap = holidayObj.getJSONObject(key);
            Boolean hasHoliday = holidayMap.getBool("holiday");
            if (hasHoliday) {
                dayList.add(holidayMap.getStr("date"));
            }
        }
        return dayList;
    }

    /**
     * 发送get请求
     */
    private static String getByUrl2(String url) {
        // 创建HTTPS GET请求
        HttpRequest request = HttpRequest.get(url)
                .header("User-Agent", "Hutool HttpRequest");

        // 发送请求并获取响应
        HttpResponse response = request.execute();

        // 输出响应的内容
        return response.body();
    }

    /**
     * 发送get请求
     */
    private static String getByUrl(String url) {
        StringBuilder inputLine = new StringBuilder();
        String read;
        try {
            HttpURLConnection urlConnection = (HttpURLConnection) new java.net.URL(url).openConnection();
            urlConnection.setReadTimeout(5 * 1000);
            urlConnection.setConnectTimeout(5 * 1000);
            urlConnection.setRequestProperty("Charset", "UTF-8");
            urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.46.172.200 Safari/537.36)");
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), StandardCharsets.UTF_8));
            while ((read = in.readLine()) != null) {
                inputLine.append(read);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return inputLine.toString();
    }

}
